//
//  ChatListViewController.m
//  GolfFriend
//
//  Created by vescky on 13-12-16.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "ChatListViewController.h"
#import "ChatListViewCell.h"
#import "UserSession.h"
#import "AppsEngine.h"
#import "ContactBookViewController.h"
#import "ChatDAO.h"
#import "OneToOneChatViewController.h"
#import "DateUtility.h"
#import "AppDelegate.h"

@interface ChatListViewController ()<UITableViewDataSource,UITableViewDelegate> {
    NSMutableArray *recentlyChatList;
}
@end

@implementation ChatListViewController

#pragma mark - life cycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setTitle:@"消息"];
    [super customBackButton];
   
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshChatList];
    [APP_DELEGATE closeMesageStatusBarAlert];
    if (ShowToolbarInWindow) {
        [APP_DELEGATE setToolbarHidden:NO];
        [self.navigationItem setHidesBackButton:YES animated:NO];
    }
    
    //发送已读消息的广播
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Chat_Read object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

#pragma mark - Private
- (void)initView {
    //定制自己的风格的  UIBarButtonItem
    UIButton* jumpButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 4, 34, 36)];//
    [jumpButton setBackgroundImage:[UIImage imageNamed:@"contactbook_white.png"] forState:UIControlStateNormal];
    [jumpButton addTarget:self action:@selector(jumpToContactBook) forControlEvents:UIControlEventTouchUpInside];
//    [jumpButton setTitle:@"通讯录" forState:UIControlStateNormal];
//    [jumpButton.titleLabel setFont:[UIFont boldSystemFontOfSize:13.0]];
    UIBarButtonItem* actionItem= [[UIBarButtonItem alloc] initWithCustomView:jumpButton];
    [self.navigationItem setRightBarButtonItem:actionItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshChatList) name:Notification_Chat_Recieved object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshChatList) name:Notification_ContactBook_Refreshed object:nil];
    
    [self.navigationController.navigationBar setHidden:NO];
    [self.navigationItem setHidesBackButton:YES animated:NO];
}

- (void)refreshChatList {
    [self loadMessages];
    if (!recentlyChatList || [recentlyChatList count] < 1) {
        //最近没有消息
        [tbChatList setHidden:YES];
        [self.view addSubview:noDataView];
    }
}

- (void)jumpToContactBook {
    ContactBookViewController *vc = [[ContactBookViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)loadMessages {
    //获取未读消息
    NSMutableArray *arr = [[ChatDAO shareChatDAO] getAllUnreadMessages];
    //获取最近聊天列表
    NSMutableArray *recentlyUserList = [[UserSession shareUserSession] getRecetlyChatWindows];
    for (int i = 0; i < [recentlyUserList count]; i++) {
        NSMutableDictionary *msgContent = [[NSMutableDictionary alloc] initWithDictionary:[[ChatDAO shareChatDAO] getLatestMessageByUserId:[recentlyUserList objectAtIndex:i]]];
        if (isValueSet(msgContent)) {
            [arr addObject:msgContent];
        }
    }
    
    for (int i = 0; i < [arr count]; i++) {
        NSMutableDictionary *msgContent = [[NSMutableDictionary alloc] initWithDictionary:[arr objectAtIndex:i]];
        if (isValueSet(msgContent)) {
            if ([[msgContent objectForKey:@"msgType"] isEqualToString:@"2"]) {
                [msgContent setObject:@"[图片]" forKey:@"content"];
            }
            [arr replaceObjectAtIndex:i withObject:msgContent];
        }
    }
    
    //合并相同fromId的消息
    NSMutableDictionary *listDict = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < [arr count]; i++) {
        NSDictionary *msgContent = [arr objectAtIndex:i];
        NSString *userId = [msgContent objectForKey:@"fromId"];
        if ([userId isEqualToString:[[UserSession shareUserSession] getUserId]]) {
            userId = [msgContent objectForKey:@"toId"];
        }
        if (isValueSet(userId)) {
            //不能覆盖较晚的消息
            if ([self isMessage:[listDict objectForKey:userId] laterThen:msgContent]) {
                continue;
            }
            [listDict setObject:msgContent forKey:userId];
        }
    }
    NSMutableArray *cList = [[NSMutableArray alloc] init];
    NSEnumerator *enm = [listDict keyEnumerator];
    for (NSString *key in enm) {
        [cList addObject:[listDict objectForKey:key]];
    }
    
    //排列消息列表
    recentlyChatList = [self resortMessagesByTimeDesc:cList];
    
    for (int i = 0; i < [recentlyChatList count]; i++) {
        NSDictionary *dict = [recentlyChatList objectAtIndex:i];
        NSString *idString = [dict objectForKey:@"fromId"];
        [[UserSession shareUserSession] saveChatWindow:idString];
    }
    
    [tbChatList reloadData];
    
}

- (bool)isMessage:(NSDictionary*)msg1 laterThen:(NSDictionary*)msg2 {
    NSString *timeString1 = [msg1 objectForKey:@"time"];
    NSString *timeString2 = [msg2 objectForKey:@"time"];
    NSDate *date1 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", timeString1);
    NSDate *date2 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", timeString2);
    
    if ([date1 isEqualToDate:[date1 laterDate:date2]]) {
        return YES;
    }
    
    return NO;
}

- (NSMutableArray*)resortMessagesByTimeDesc:(NSArray*)mArr {
    //按时间排序，从晚到早
    NSArray *sortedArr = [mArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//        NSDictionary *dict1 = [[ChatDAO shareChatDAO] getLatestMessageByUserId:obj1];
//        NSDictionary *dict2 = [[ChatDAO shareChatDAO] getLatestMessageByUserId:obj2];
//        NSString *timeString1 = [obj1 objectForKey:@"timeString"];
//        NSString *timeString2 = [obj2 objectForKey:@"timeString"];
//        NSDate *date1 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", timeString1);
//        NSDate *date2 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", timeString2);
//        
//        if ([date1 isEqualToDate:[date1 laterDate:date2]]) {
//            return (NSComparisonResult)NSOrderedDescending;
//        }
//        else {
//            return (NSComparisonResult)NSOrderedAscending;
//        }
//        
//        return (NSComparisonResult)NSOrderedSame;
        if ([self isMessage:obj1 laterThen:obj2]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        else {
            return (NSComparisonResult)NSOrderedDescending;
        }
    }];
    return [[NSMutableArray alloc] initWithArray:sortedArr];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [recentlyChatList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"ChatListViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ChatListViewCell" owner:self options:nil] objectAtIndex:0];
//        cell = [[ChatListViewCell alloc] init];
    }
    
    if ([cell respondsToSelector:@selector(setDataInfo:)]) {
        [cell performSelector:@selector(setDataInfo:) withObject:[recentlyChatList objectAtIndex:indexPath.row]];
    }
    
    [cell setTag:200+indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tbChatList deselectRowAtIndexPath:indexPath animated:YES];
    OneToOneChatViewController *ochatVc = [[OneToOneChatViewController alloc] init];
    NSString *userId = [[recentlyChatList objectAtIndex:indexPath.row] objectForKey:@"fromId"];
    if ([userId isEqualToString:[[UserSession shareUserSession] getUserId]]) {
        userId = [[recentlyChatList objectAtIndex:indexPath.row] objectForKey:@"toId"];
    }
    ochatVc.userId = userId;
    [self.navigationController pushViewController:ochatVc animated:YES];
}

@end
